package auth

import (
	"context"
	"errors"

	"usercenter/internal/svc"
	"usercenter/internal/types"
	"usercenter/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginRequest) (resp *types.UserLoginResponse, err error) {
	// 1. 验证用户信息
	user, err := l.svcCtx.UserModel.FindByEmail(req.Email)
	if user == nil {
		return nil, errors.New("用户不存在或密码错误")
	}
	if err != nil {
		return nil, errors.New("系统错误")
	}
	// 2. 验证密码
	if !user.CheckPassword(req.Password) {
		return nil, errors.New("用户不存在或密码错误")
	}

	// 3. 生成双token
	authConf := utils.AuthConfig{
		AccessSecret:  l.svcCtx.Config.JWT.AccessSecret,
		AccessExpire:  l.svcCtx.Config.JWT.AccessExpire,
		RefreshSecret: l.svcCtx.Config.JWT.RefreshSecret,
		RefreshExpire: l.svcCtx.Config.JWT.RefreshExpire,
	}

	accessToken, refreshToken, err := utils.GenerateTokenPair(int(user.ID), authConf)
	if err != nil {
		logx.Errorf("生成token失败: %v", err)
		return nil, errors.New("登录失败")
	}

	// 4. 存储refreshToken
	tokenStore := utils.NewTokenStore(l.svcCtx.Redis, int(l.svcCtx.Config.JWT.RefreshExpire))
	if err := tokenStore.StoreRefreshToken(l.ctx, int(user.ID), refreshToken); err != nil {
		logx.Errorf("存储refreshToken失败: %v", err)
		return nil, errors.New("系统错误")
	}

	return &types.UserLoginResponse{
		Code:    200,
		Message: "success",
		Data: types.LoginData{
			AccessToken:  accessToken,
			RefreshToken: refreshToken,
		},
	}, nil
}
